#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
    int client_sock;
    if (argc != 3) {
        printf("Usage : %s <IP> <port>\n", argv[0]);
        exit(1);
    }
    if ((client_sock = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        error_handling("socket() error!");
    }
    
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    server_addr.sin_port = htons(atoi(argv[2]));

    if (connect(client_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        error_handling("connect() error!");
    }
    

    char message[30];
    int idx = 0;
    int str_len = 0, read_len = 0;
    while (read_len = read(client_sock, &message[idx++], 1)) {
        if (read_len == -1)
            error_handling("read() error!");
        str_len += read_len;
    }
    printf("Message from server : %s \n", message);
    printf("read call count: %d\n", str_len);
//    close(client_sock);
    return 0;
}